package job

import (
	"context"
	"gitee.com/chicken-c/go-learn/webook/internal/service"
	rlock "github.com/gotomicro/redis-lock"
	"time"
)

type RankingJob struct {
	svc service.RankingService

	//这里的时间就是我们执行定时任务的超时时间
	timeout time.Duration
	//分布式锁
	lock rlock.Client
	key  string
}

func NewRankingJob(svc service.RankingService, timeout time.Duration) Job {
	return &RankingJob{
		svc:     svc,
		timeout: timeout,
		key:     "job:ranking",
	}
}

func (r *RankingJob) Name() string {
	return "ranking"
}

func (r *RankingJob) Run() error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
	defer cancel()
	//获取分布式锁
	lock, err := r.lock.Lock(ctx, r.key, r.timeout, &rlock.FixIntervalRetry{
		Interval: time.Millisecond * 100,
		Max:      3,
	}, time.Second)
	//获取失败，比用特别处理，我们相信其他节点会拿到锁
	if err != nil {
		return err
	}

	defer func() {
		//解锁
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()
		er := lock.Unlock(ctx)
		if er != nil {
			//解锁失败，打印日志
			//不需要进行处理，因为我们为分布式锁设置了过期时间
		}
	}()

	//计算TopN
	ctx, cancel = context.WithTimeout(context.Background(), r.timeout)
	defer cancel()
	return r.svc.TopN(ctx)
}
